import { useParams } from 'react-router-dom'
import { useRequest } from 'ahooks'
// import { useState, useEffect } from 'react'
import { getQuestionService } from '../service/question'
import { useDispatch } from 'react-redux'
import { useEffect } from 'react'
import { resetComponents } from '../store/componentsReducer'
function useLoadQuestionData() {
  const { id = '' } = useParams()
  const dispatch = useDispatch()

  const { data, loading, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error('no id')
      const data = await getQuestionService(id)
      console.log('data', data)
      return data
    },
    {
      manual: true,
    }
  )
  useEffect(() => {
    console.log('data---------', data)
    if (!data) return
    const { title = '', componentList = [] } = data
    // 获取默认的 selectedId
    let selectedId = ''
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id // 默认选中第一个组件
    }
    dispatch(resetComponents({ componentList, selectedId }))
  }, [data])

  useEffect(() => {
    run(id)
  }, [id])
  return { loading, error }
}

export default useLoadQuestionData
